package de.pa2.proxy;

public class MiscUtils {
	public static boolean hostnameMatches(String patternHostname,
			String requestedHostname) {
		
		if (requestedHostname == null)
			throw new IllegalArgumentException("requestedHostname must not be null");
		
		if (!patternHostname.contains("*")) {
			return patternHostname.equals(requestedHostname);
		}

		// split parts by .
		String[] patternParts = patternHostname.split("\\.");
		String[] requestedParts = requestedHostname.split("\\.");

		if (patternParts.length != requestedParts.length)
			return false;

		for (int i = requestedParts.length - 1; i >= 0; i--) {
			String requestedPart = requestedParts[i];
			String patternPart = patternParts[i];

			if (!"*".equals(patternPart)) {
				// check that the parts equal
				if (!requestedPart.equals(patternPart)) {
					return false;
				}
			} else {
				// everything matches *
			}
		}
		return true;
	}
}
